package dao

import (
	"blog/conf"
	"blog/model"
	"github.com/zxysilent/logs"
	"log"
	"xorm.io/xorm"
	xlog "xorm.io/xorm/log"
)

// Db 数据库操作句柄
var Db *xorm.Engine

func Init() {
	// 初始化数据库操作的 Xorm
	db, err := xorm.NewEngine("mysql", conf.AppConf.Dsn())
	if err != nil {
		logs.Fatal("数据库 dsn:", err.Error())
	}
	sl := &xlog.SimpleLogger{
		DEBUG: log.New(logs.Writer(), "", log.Ldate|log.Ltime),
		ERR:   log.New(logs.Writer(), "", log.Ldate|log.Ltime),
		INFO:  log.New(logs.Writer(), "", log.Ldate|log.Ltime),
		WARN:  log.New(logs.Writer(), "", log.Ldate|log.Ltime),
	}
	sl.SetLevel(xlog.LOG_INFO)
	db.SetLogger(sl)

	if err = db.Ping(); err != nil {
		logs.Fatal("数据库 ping:", err.Error())
	}
	db.SetMaxIdleConns(4)
	db.SetMaxOpenConns(8)
	// 是否显示sql执行的语句
	db.ShowSQL(true)

	// mysql int(11)、tinyint(4)、smallint(6)、mediumint(9)、bigint(20)
	_ = db.Sync2(
		// appConf
		new(model.Article),
		// smodel.ys
		new(model.ArticleExtend),
		new(model.Topic),
		new(model.Iprecord),
	)
	if err != nil {
		logs.Fatal("数据库 sync:", err.Error())
	}
	Db = db
	//缓存
	//initGlobal()
	logs.Info("model init")
}

func Close() {
	_ = Db.Close()
}
